package com.springboot3login.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.springboot3login.domain.vo.CaptchaVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
 
/**
 * @author 验证码
 */
@RestController
@RequestMapping("/Captcha")
@Tag(name = "验证码接口", description = "验证码接口相关操作")
@Slf4j
public class CaptchaController {
    private final StringRedisTemplate stringRedisTemplate;
 
    public CaptchaController(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    
    @GetMapping("/graph-captcha")
    @Operation(summary = "获取验证码")
    public CaptchaVO getCaptcha(String captchaId) {
        // 创建一个图像验证码宽度为130，高度为48，包含4个字符，干扰线10个
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(130, 48, 4, 10);
        // 获取验证码的文本
        String captchaText = circleCaptcha.getCode();
        // 获取验证码图片的Base64编码
        String captchaImageBase64Data = circleCaptcha.getImageBase64Data();
        // 如果没有传入captchaId，则生成一个随机字符串作为captchaId
        captchaId = Optional.ofNullable(captchaId).orElseGet(() -> UUID.randomUUID().toString());
        // 保存验证码文本到Redis中，有效期30秒
        stringRedisTemplate.opsForValue().set("captcha:" + captchaId, captchaText, 30, TimeUnit.MINUTES);

        log.info("captchaId: {},captchaText:{}", captchaId,captchaText);
        return CaptchaVO.builder()
                .captchaId(captchaId)
                .captchaImage(captchaImageBase64Data)
                .build();
    }

    @SneakyThrows
    @GetMapping("/graph-captchaBrowser")
    @Operation(summary = "获取验证码")
    public void getCaptchaBrowser(HttpServletResponse response) {
        // 创建一个图像验证码宽度为130，高度为48，包含4个字符，干扰线10个
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(130, 48, 4, 10);
        log.info("验证码是：{}",circleCaptcha.getCode());
        //写出到浏览器
        try (OutputStream out = response.getOutputStream()) {
            circleCaptcha.write(out);
        }
    }
 
}